package com.hd.ssm.controller;


import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.hd.ssm.entity.User;
import com.hd.ssm.service.IUserService;


@Controller
@RequestMapping("user/")
public class UserController{
	
	@Resource
	private IUserService userService;
	
	@RequestMapping("getUserList.action")
	@ResponseBody
	public List<User> getUserList(HttpServletRequest req, HttpServletResponse response) {
	    
		List<User> users = userService.getUserList();	
		return users;
	}

	@RequestMapping("saveUser.action")
	@ResponseBody
	public String saveUser(HttpServletRequest req, HttpServletResponse response){
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		int age = Integer.parseInt(req.getParameter("age"));
		User user = new User();
		user.setUsername(username);
		user.setPassword(password);
		user.setAge(age);
		userService.saveUser(user);
		return "redirect:getUserList.action";
	}
	
	@RequestMapping("editUserById.action")
	@ResponseBody
	public String editUserById(HttpServletRequest req, HttpServletResponse response){
		String result = "fail";
		String id = req.getParameter("id");
		try {
			userService.delUserById(Integer.valueOf(id));
			result = "success";
		} catch (Exception e) {
			
		}
		return result;
	}
	
	@RequestMapping("deleteUserById.action")
	public String deleteUserById(HttpServletRequest req, HttpServletResponse response){
		int userId = Integer.parseInt(req.getParameter("id"));
		int n = userService.delUserById(userId);
		System.out.println("n="+n);
		return "redirect:getUserList.action";
	}
}